﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using Blade.Metadata.CliLoader;
using Blade.IO;

namespace Blade.Metadata {
	public abstract class CliMetadataLoaderBase : MetadataLoaderBase {
		public CliMetadataLoaderBase(IServiceProvider services)
			: base(services.GetService<IMetadataPlatform>()) {
			this.Services = services;
			this.Locator = services.GetService<IMetadataLocator>();
		}

		public IServiceProvider Services { get; private set; } 
		public IMetadataLocator Locator { get; private set; }

		const int DOS_HEADER_LFANEW_OFFSET = 0x3C; // ECMA-335 Partition II, §25.2.1
		static readonly char[] PE_SIGNATURE = new char[] { 'P', 'E', '\0', '\0' }; // Partition II, §25.2.1

		protected sealed override IAssemblyDefinition LoadAssemblyCore(AssemblyName name, IMetadataLoaderContext context) {
			MemoryCursorStream fileStream;
			using (var stream = Locator.OpenAssembly(name)) {
				int length = (int)stream.Length;
				var assemblyBytes = new byte[length];
				var read = stream.Read(assemblyBytes, 0, length);
				if (read != length) {
					throw new IOException();
				}
				fileStream = new MemoryCursorStream(assemblyBytes, false);
			}
			var fileReader = CreateFileReader(fileStream, context);
			var metadata = new CliMetadataFile(fileReader, context);
			throw new NotImplementedException();
		}

		protected abstract ICliFileReader CreateFileReader(CursorStream fileStream, IMetadataLoaderContext context);
	}
}
